package com.agileai.portal.portlets.bar;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import javax.portlet.PortletModeException;
import javax.portlet.PortletPreferences;
import javax.portlet.PortletResponse;
import javax.portlet.ProcessAction;
import javax.portlet.ReadOnlyException;
import javax.portlet.RenderMode;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;
import javax.portlet.ValidatorException;

import org.apache.pluto.container.PortletRequestContext;

import com.agileai.domain.DataParam;
import com.agileai.domain.DataRow;
import com.agileai.hotweb.common.BeanFactory;
import com.agileai.portal.bizmoduler.bar.ExtBarLinkManage;
import com.agileai.portal.bizmoduler.bar.ExtGeneralQueryConfigManage;
import com.agileai.portal.driver.AttributeKeys;
import com.agileai.portal.driver.Resource;
import com.agileai.portal.driver.common.PortletRequestHelper;
import com.agileai.portal.driver.common.PreferenceException;
import com.agileai.portal.driver.common.PreferencesHelper;
import com.agileai.portal.driver.common.PreferencesWrapper;
import com.agileai.portal.driver.model.Page;
import com.agileai.portal.driver.servlet.ParamInteractiveServlet;
import com.agileai.portal.portlets.BaseMashupPortlet;
import com.agileai.portal.portlets.PortletCacheManager;
import com.agileai.util.DateUtil;
import com.agileai.util.ListUtil;
import com.agileai.util.StringUtil;

public class GeneralSelecterPortlet extends BaseMashupPortlet {
	private static final String NEW_LINE = "\r\n";
	
	@RenderMode(name="view")
	public void view(RenderRequest request, RenderResponse response) throws PortletException, IOException {
		PortletPreferences preferences = PreferencesHelper.getPublicPreference(request);
		
		String isExtendLink = preferences.getValue("isExtendLink", "N");		
		String extendEnumDataURL = preferences.getValue("extendEnumDataURL", "");
		String isConvertText = preferences.getValue("isConvertText", "Y");

		PortletRequestContext requestContext = PortletRequestHelper.getRequestContext(request);
		Page page = (Page)requestContext.getAttribute(AttributeKeys.PAGE_KEY);
		
		String pageId = page.getPageId();
		String portletId = request.getWindowID();
		String isSetting = "false";
		
		ExtGeneralQueryConfigManage extConfigManage = (ExtGeneralQueryConfigManage)BeanFactory.instance().getBean("extGeneralQueryConfigManageService");
		DataParam param = new DataParam();
		param.put("pageId",pageId,"portletId",portletId);
		
		List<DataRow> extConfigRecords = extConfigManage.findRecords(param);
		if(extConfigRecords.size()>0){
			isSetting = "true";
		}
		HashMap<String,String> onchangeHandlerMap = new HashMap<String,String>();
		onchangeHandlerMap.put("onchangeHandler","");
		HashMap<String,String> defaultViriableMap = new HashMap<String,String>();
		defaultViriableMap.put("defaultViriable","");
		
		String extBarSyntax = this.buildExtendFormArea(extConfigRecords,response,onchangeHandlerMap,defaultViriableMap);
		request.setAttribute("extBarSyntax", extBarSyntax);
		
		String onchangeHandler = onchangeHandlerMap.get("onchangeHandler");
		request.setAttribute("onchangeHandler",onchangeHandler);
		String defaultViriable = defaultViriableMap.get("defaultViriable");
		request.setAttribute("defaultViriable",defaultViriable);
			
		request.setAttribute("portletId",portletId);
		request.setAttribute("isSetting",isSetting);
		request.setAttribute("isExtendLink", isExtendLink);
		request.setAttribute("extendEnumDataURL", extendEnumDataURL);	
		request.setAttribute("isConvertText", isConvertText);
		
		if ("Y".equals(isExtendLink)){
			ExtBarLinkManage extBarLinkManage = (ExtBarLinkManage)BeanFactory.instance().getBean("extBarLinkManageService");
			List<DataRow> extBarLinkRecords = extBarLinkManage.findRecords(param);
			String extBarLinkSyntax = this.buildExtendLinkArea(extBarLinkRecords);
			request.setAttribute("extBarLinkSyntax", extBarLinkSyntax);
		}
		
		super.doView(request, response);
	}
	
	private String buildExtendFormArea(List<DataRow> extConfigRecords,PortletResponse response,HashMap<String,String> onchangeHandlerMap,HashMap<String,String> defaultViriableMap){
		StringBuffer extBar = new StringBuffer();
		String defaultViriable = "[";
		String dateFields[] = {"BeginOfCurrentMonth","BeginOfCurrentYear","EndOfCurrentMonth","EndinOfCurrentYear","TheDayBeforeYesterday","Today","Yesterdy","Tomorrow","TheDayAfterTomorrow"};
		if (!ListUtil.isNullOrEmpty(extConfigRecords)){
			int count = extConfigRecords.size();
			String namespace = response.getNamespace();
			for (int i=0;i < count;i++){
				DataRow row = extConfigRecords.get(i);
				String code = row.stringValue("CODE");
				String label = row.stringValue("LABEL");
				String fieldType = row.stringValue("FIELD_TYPE");
				String width = row.stringValue("DISPLAY_LENGTH");
				String breakLine = row.stringValue("BREAK_LINE");
				String trigerCascade = row.stringValue("TRIGER_CASCADE");
				String immediateTrigger = row.stringValue("IMMEDIATE_TRIGGER");
				String defaultValues = row.stringValue("DEFAULT_VALUES");
				
				String onKeyPressHandler = "";
				String onchangeHandler = "";
				if ("TEXT".equals(fieldType)){
					if ("Y".equals(immediateTrigger)){
						onKeyPressHandler = "enterPress"+namespace+"();";	
					}
					extBar.append("<span style='margin:auto 5px;' id='").append(code).append("Span'>").append(NEW_LINE);
					extBar.append("<label style='margin-right:3px'>").append(label).append("</label><input id='").append(code).append("' name='").append(code).append("' type='text' style='width:").append(width).append("px' value='' onkeypress='").append(onKeyPressHandler).append("'/>").append(NEW_LINE);
					extBar.append("</span>").append(NEW_LINE);
					if ("Y".equals(breakLine)){
						extBar.append("<br />");
					}
				}
				else if ("DATEPICK".equals(fieldType)){
					if ("Y".equals(immediateTrigger)){
						onKeyPressHandler = "enterPress"+namespace+"();";	
					}
					extBar.append("<span style='margin:auto 5px;' id='").append(code).append("Span'>");
					
					extBar.append("<label style='margin-right:3px;'>").append(label).append("</label><input id='").append(code).append("' name='").append(code).append("' type='text' onkeypress='").append(onKeyPressHandler).append("'/> <img id='").append(code).append("Picker' src='images/calendar.gif' width='16' height='16' alt='日期/时间选择框' />");
					extBar.append("</span>");
					if ("Y".equals(breakLine)){
						extBar.append("<br />");
					}
					int flag = 0;
					if(StringUtil.isNullOrEmpty(defaultValues)){
						flag = 1;
					}
					for (int j = 0; j < dateFields.length; j++ )
					{
					   if ( dateFields[j].equals(defaultValues) )
					   {
					      flag = 1;
					      break;
					   }
					}
					if(flag==1){
						defaultValues = getRealDate(defaultValues);
					}
				}
				else if ("TIMEPICK".equals(fieldType)){
					if ("Y".equals(immediateTrigger)){
						onKeyPressHandler = "enterPress"+namespace+"();";
					}
					extBar.append("<span style='margin:auto 5px;' id='").append(code).append("Span'>");
					extBar.append("<label style='margin-right:3px;'>").append(label).append("</label><input id='").append(code).append("' name='").append(code).append("' type='text' onkeypress='").append(onKeyPressHandler).append("'/> <img id='").append(code).append("Picker' src='images/calendar.gif' width='16' height='16' alt='日期/时间选择框' />");
					extBar.append("</span>");
					if ("Y".equals(breakLine)){
						extBar.append("<br />");
					}
					if(StringUtil.isNullOrEmpty(defaultValues)){
						defaultValues = DateUtil.getDateByType(11, new Date());
					}
				}
				else if ("SELECT".equals(fieldType)){
					if ("Y".equals(trigerCascade)){
						onchangeHandler = "doReloadQueryBar"+namespace+"();";
					}
					if ("Y".equals(immediateTrigger)){
						onchangeHandler = "doSearch"+namespace+"();";
					}
					extBar.append("<span style='margin:auto 5px;' id='").append(code).append("Span'>");
					extBar.append("<label style='margin-right:3px;'>").append(label).append("</label><select id='").append(code).append("' name='").append(code).append("' style='width:").append(width).append("px' onchange='").append(onchangeHandler).append("'></select>");
					extBar.append("</span>");
					if ("Y".equals(breakLine)){
						extBar.append("<br />");
					}					
				}
				else if ("CHECKBOX".equals(fieldType)){
					if ("Y".equals(trigerCascade)){
						onchangeHandler = "doReloadQueryBar"+namespace+"();";
					}
					if ("Y".equals(immediateTrigger)){
						onchangeHandler = "doSearch"+namespace+"();";
					}
					onchangeHandlerMap.put("onchangeHandler", onchangeHandler);
					extBar.append("<span style='margin:auto 5px;display:inline-block;' id='").append(code).append("Span'>");
					extBar.append(onchangeHandler).append("</span>");
					if ("Y".equals(breakLine)){
						extBar.append("<br />");
					}					
				}
				if("SELECT".equals(fieldType)||"CHECKBOX".equals(fieldType)){
					defaultViriable += "{id:'" + code + "',type:'" + fieldType + "',values:" + defaultValues + "},"; 
				}else{
					defaultViriable += "{id:'" + code + "',type:'" + fieldType + "',value:'" + defaultValues + "'},"; 
				}
			}
		}
		defaultViriable = defaultViriable.substring(0, defaultViriable.length()-1);
		defaultViriable += "]";
		defaultViriableMap.put("defaultViriable", defaultViriable);
		return extBar.toString();
	}
	
	private String buildExtendLinkArea(List<DataRow> extBarLinkRecords){
		StringBuffer extBarLink = new StringBuffer();
		if (!ListUtil.isNullOrEmpty(extBarLinkRecords)){
			int count = extBarLinkRecords.size();
			for (int i=0;i < count;i++){
				DataRow row = extBarLinkRecords.get(i);
				String name = row.stringValue("NAME");
				String linkURL = row.stringValue("LINK_URL");
				String newPage = row.stringValue("NEW_PAGE");
				if ("N".equals(newPage)){
					extBarLink.append("<a hidefocus=\"true\" href=\"javascript:doLinkPortalPage('").append(linkURL).append("',false)\" class=\"button-link blue\">").append(name).append("</a>&nbsp;");
				}else{
					extBarLink.append("<a hidefocus=\"true\" href=\"javascript:doLinkPortalPage('").append(linkURL).append("',true)\" class=\"button-link blue\">").append(name).append("</a>&nbsp;");
				}
			}
		}
		return extBarLink.toString();
	}
	
	private String getRealDate(String defaultDate){
		String result = "";
		if (StringUtil.isNullOrEmpty(defaultDate)){
			result = DateUtil.getDateByType(DateUtil.YYMMDD_HORIZONTAL,new Date());
		} else if (ParamInteractiveServlet.VariableKeys.Today.equals(defaultDate)){
			result = DateUtil.getDateByType(DateUtil.YYMMDD_HORIZONTAL,new Date());
		} else if (ParamInteractiveServlet.VariableKeys.Tomorrow.equals(defaultDate)){
			result = DateUtil.getDateByType(DateUtil.YYMMDD_HORIZONTAL,DateUtil.getDateAdd(new Date(), DateUtil.DAY, 1));
		} else if (ParamInteractiveServlet.VariableKeys.Yesterdy.equals(defaultDate)){
			result = DateUtil.getDateByType(DateUtil.YYMMDD_HORIZONTAL,DateUtil.getDateAdd(new Date(), DateUtil.DAY, -1));
		}else if (ParamInteractiveServlet.VariableKeys.BeginOfCurrentMonth.equals(defaultDate)){
			result = DateUtil.getDateByType(DateUtil.YYMMDD_HORIZONTAL,DateUtil.getBeginOfMonth(new Date()));
		}else if (ParamInteractiveServlet.VariableKeys.BeginOfCurrentYear.equals(defaultDate)){
			result = DateUtil.getDateByType(DateUtil.YYMMDD_HORIZONTAL,DateUtil.getBeginOfYear(new Date()));
		}else if (ParamInteractiveServlet.VariableKeys.EndOfCurrentMonth.equals(defaultDate)){
			result = DateUtil.getDateByType(DateUtil.YYMMDD_HORIZONTAL,DateUtil.getEndOfMonth(new Date()));
		}else if (ParamInteractiveServlet.VariableKeys.EndinOfCurrentYear.equals(defaultDate)){
			Date beginOfCurrentYear = DateUtil.getBeginOfYear(new Date());
			Date beginOfNextYear = DateUtil.getDateAdd(DateUtil.getBeginOfYear(beginOfCurrentYear), DateUtil.YEAR,1);
			Date endOfCurrentYear = DateUtil.getDateAdd(beginOfNextYear,DateUtil.DAY,-1);
			result = DateUtil.getDateByType(DateUtil.YYMMDD_HORIZONTAL,endOfCurrentYear);
		}else if (ParamInteractiveServlet.VariableKeys.TheDayBeforeYesterday.equals(defaultDate)){
			result = DateUtil.getDateByType(DateUtil.YYMMDD_HORIZONTAL,DateUtil.getDateAdd(new Date(), DateUtil.DAY, -2));
		}else if (ParamInteractiveServlet.VariableKeys.TheDayAfterTomorrow.equals(defaultDate)){
			result = DateUtil.getDateByType(DateUtil.YYMMDD_HORIZONTAL,DateUtil.getDateAdd(new Date(), DateUtil.DAY, 2));
		}
		
		return result;
	}
	
	@RenderMode(name="edit")
	public void edit(RenderRequest request, RenderResponse response) throws PortletException, IOException {
	
		PortletPreferences preferences = PreferencesHelper.getPublicPreference(request);
		String isExtendLink = preferences.getValue("isExtendLink", "N");		
		String extendEnumDataURL = preferences.getValue("extendEnumDataURL", "");
		String isConvertText = preferences.getValue("isConvertText", "Y");

		request.setAttribute("isExtendLink", isExtendLink);
		request.setAttribute("extendEnumDataURL", extendEnumDataURL);
		request.setAttribute("isConvertText", isConvertText);
		
		PortletRequestContext requestContext = PortletRequestHelper.getRequestContext(request);
		Page page = (Page)requestContext.getAttribute(AttributeKeys.PAGE_KEY);
		
		String pageId = page.getPageId();
		String portletId = request.getWindowID();
		request.setAttribute("pageId", pageId);
		request.setAttribute("portletId", portletId);
		
		super.doEdit(request, response);
	}
	
	@ProcessAction(name = "saveConfig")
	public void saveConfig(ActionRequest request, ActionResponse response)
			throws ReadOnlyException, PortletModeException, ValidatorException, IOException, PreferenceException {
		
		String isExtendLink = request.getParameter("isExtendLink");
		String extendEnumDataURL = request.getParameter("extendEnumDataURL");
		String isConvertText = request.getParameter("isConvertText");
		
		PreferencesWrapper preferWrapper = new PreferencesWrapper();		
		preferWrapper.setValue("isExtendLink", isExtendLink);
		preferWrapper.setValue("extendEnumDataURL", extendEnumDataURL);
		preferWrapper.setValue("isConvertText", isConvertText);
		
		PreferencesHelper.savePublicPreferences(request, preferWrapper.getPreferences());
		response.setPortletMode(PortletMode.VIEW);
	}
	
	@Resource(id="getAjaxData")
	public void getAjaxData(ResourceRequest request, ResourceResponse response)
			throws PortletException, IOException {
		String ajaxData = "";
		try {
			PortletPreferences preferences = PreferencesHelper.getPublicPreference(request);
			String cacheMinutes = (String)preferences.getValue("cacheMinutes",defaultCacheMinutes);
			String isCache = preferences.getValue("isCache", defaultIsCache);
			String dataURL = getDataURL(request,"extendEnumDataURL");
			ajaxData = PortletCacheManager.getOnly().getCachedData(isCache, dataURL, cacheMinutes);
		} catch (Exception e) {
			this.logger.error("获取取数据失败getAjaxData", e);
		}
		PrintWriter writer = response.getWriter();
		writer.print(ajaxData);
		writer.close();
	}
}